package org.misalen.web.admin.shiro;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.misalen.web.database.model.mysql.sys.SysAdmin;
import org.misalen.web.database.repository.mysql.SysAdminRepository;
import org.misalen.web.database.repository.mysql.SysRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * shiro 自定义用户认证
 * 
 * @author guochao
 *
 */
public class ShiroDbRealm extends AuthorizingRealm {

	@Autowired
	protected SysAdminRepository sysAdminRepository;
	@Autowired
	protected SysRoleRepository sysRoleRepository;
	private static final Logger LOGGER = LogManager.getLogger(ShiroDbRealm.class);

	/**
	 * Shiro登录认证(认证 密码 状态 )
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		LOGGER.info("Shiro开始登录认证");
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		SysAdmin sysAdmin = sysAdminRepository.get("from SysAdmin where username=?0",
				new Object[] { token.getUsername() });
		if (sysAdmin == null) {
			throw new UnknownAccountException();
		}
		ShiroUser shiroUser = new ShiroUser(sysAdmin.getPrimaryKey(), sysAdmin.getNickname(), sysAdmin.getUsername());
		Set<String> roleSet = new HashSet<String>();
		List<String> resource = sysRoleRepository.findCodeByAdmin(shiroUser.getUserId());
		for (String string : resource) {
			roleSet.add(string);
		}
		shiroUser.setRoleSet(roleSet);
		return new SimpleAuthenticationInfo(shiroUser, sysAdmin.getLoginPwd().toCharArray(), getName());

	}

	/**
	 * Shiro权限认证（添加用户所拥有的权限）
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		LOGGER.info("Shiro开始设置用户角色");
		ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addStringPermissions(shiroUser.getRoleSet());
		return info;
	}
}
